<!-- 贴图建筑地图 -->
<template>
  <div id="mapbox-container"></div>
</template>

<script setup>
import { onMounted, getCurrentInstance } from 'vue'
import mapboxgl from '../../components/mapbox/mapbox.js'
import U from 'mapbox-gl-utils'
import axios from 'axios'
import api from '../../api/geoserver'
import * as turf from '@turf/turf'
// import MapboxDraw from '@mapbox/mapbox-gl-draw'
// import MapboxLanguage from '@mapbox/mapbox-gl-language'
import { Threebox, THREE } from 'threebox-plugin'

defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})
let map = null

let mapconfig = null
// const emit = defineEmits(['onload'])
const { proxy } = getCurrentInstance()
const path = import.meta.env.VITE_APP_PATH

onMounted(() => {
  loadConfig()
})

// 同步加载底图配置信息
async function loadConfig() {
  const config = await axios.get(import.meta.env.VITE_APP_PATH + 'config/config.json').catch((err) => console.log(err))
  const style = await axios.get(import.meta.env.VITE_APP_PATH + 'config/white-v12.json').catch((err) => console.log(err))
  console.log(config.data, style)
  mapconfig = proxy.$root.$mapconfig = config.data.schoolMap
  initMap(style.data)
}

// 根据配置信息初始化地图
function initMap(style) {
  const option = mapconfig.campus[1]
  // 初始化创建mapbox地图

  map = new mapboxgl.Map({
    container: 'mapbox-container',
    style: style,
    // style: 'mapbox://styles/mapbox/dark-v11',
    center: option.center,
    zoom: option.zoom,
    pitch: 56,
    bearing: -35.2
  })
  // mapboxgl.setRTLTextPlugin(
  //   'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.3/mapbox-gl-rtl-text.js'
  // )
  // map.addControl(new MapboxLanguage({defaultLanguage: 'zh-Hans'}))
  // map.addControl(new MapboxDraw(), 'bottom-right')

  // 初始化threebox对象并加到全局环境---只能放在这，放在map创建完成后load中模型移动不生效
  // window.tb = new Threebox(map, map.getCanvas().getContext('webgl'), {
  //   defaultLights: true,
  //   // realSunlight: true,
  //   enableSelectingFeatures: true, //模型是否可以被选择
  //   enableSelectingObjects: true, //模型是否可以被选中
  //   enableDraggingObjects: true, //模型是否可以被拖动和移动
  //   enableRotatingObjects: true, //模型是否可以被旋转
  //   enableTooltips: true // 模型是否显示标签
  // })

  // 等map创建完成后加载建筑图层
  map.on('load', function () {
    // Start the animation.
    // rotateCamera(0)

    // Add 3d buildings and remove label layers to enhance the map
    // const layers = map.getStyle().layers;
    // for (let i = 0; i < layers.length; i++) {
    // console.log(layers[i]);
    // if (layers[i].type === "symbol" && layers[i].layout["text-field"]) {
    // remove text labels
    // map.removeLayer(layers[i].id)
    // }
    // }

    // 初始化mapbox工具类
    U.init(map)

    // 抛出map创建完成事件
    // emit('onload', map)
    // loadDatas()
    addChartletLyer()
  })

  // map.loadImage('./images/material/yzdm5.jpg',
  //   (error, image) => {
  //     if (error) throw error
  //     map.addImage('yzdm1', image)
  //   }
  // )

  map.on('click', function (e) {
    // console.log("----click----");
    // console.log(e.point);
    // console.log(e.lngLat);
  })
  map.on('dblclick', function (e) {
    // console.log("----dblclick----");
  })
  map.on('wheel', function () {
    // console.log("----wheel----");
    // console.log(map.getZoom());
  })
}
const parameter = {
  service: 'WFS',
  version: '1.0.0',
  request: 'GetFeature',
  maxFeatures: '10000',
  outputFormat: 'application/json'
}

// 加载图层数据
async function loadDatas() {
  map.addSource('wms-test-source', {
    type: 'raster',
    // use the tiles option to specify a WMS tile source URL
    // https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/
    tiles: [
      'http://61.52.175.217:8081/geoserver/gwc/service/wmts?layer=zzdx:zzdx_campusmap_baselayer&style=&tilematrixset=EPSG:900913&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image/png&TileMatrix=EPSG:900913:{z}&TileCol={x}&TileRow={y}'
    ],
    tileSize: 256
  })
  map.addLayer({
    id: 'wms-test-layer',
    type: 'raster',
    source: 'wms-test-source',
    paint: {}
  })


  // parameter.typeName = 'sqsfgx:dlmc_point'
  // const roadData = await api
  //   .getLayerData('sqsfgx', parameter)
  //   .catch((err) => console.log(err))

  // map.addSource('dlmc_point', {
  //   type: 'geojson',
  //   data: roadData
  // })
  // console.log('roomData', roomData)

  // map.addSource('roomData', {
  //   type: 'geojson',
  //   data: roomData
  // })
  // map.addLayer({
  //   id: 'buildings',
  //   type: 'fill-extrusion', //设置当前图层类型 此为边
  //   source: 'roomData',
  //   layout: {
  //     visibility: 'visible' //是否显影
  //   },
  //   paint: {
  //     //设置属性
  //     'fill-extrusion-color': ['get', 'color'],
  //     'fill-extrusion-height': [
  //       'interpolate',
  //       ['linear'],
  //       ['zoom'],
  //       15,
  //       0,
  //       15.05,
  //       ['get', 'height']
  //     ],
  //     'fill-extrusion-base': [
  //       'interpolate',
  //       ['linear'],
  //       ['zoom'],
  //       15,
  //       0,
  //       15.05,
  //       ['get', 'min_height']
  //     ],
  //     'fill-extrusion-opacity': 0.6
  //   }
  // })

  // parameter.typeName = 'sqsf:outside_jianzhuwu'
  // const outbuildingData = await api
  //   .getLayerData('sqsf', parameter)
  //   .catch((err) => console.log(err))

  // map.addSource('outside_jianzhuwu', {
  //   type: 'geojson',
  //   data: outbuildingData
  // })
  // map.addLayer({
  //   id: 'outbuildings',
  //   type: 'fill-extrusion', //设置当前图层类型 此为边
  //   source: 'outside_jianzhuwu',
  //   layout: {
  //     visibility: 'visible' //是否显影
  //   },
  //   paint: {
  //     //设置属性
  //     'fill-extrusion-color': '#bfeeec',
  //     'fill-extrusion-height': [
  //       'interpolate',
  //       ['linear'],
  //       ['zoom'],
  //       15,
  //       0,
  //       15.05,
  //       ['get', 'height']
  //     ],
  //     'fill-extrusion-base': [
  //       'interpolate',
  //       ['linear'],
  //       ['zoom'],
  //       15,
  //       0,
  //       15.05,
  //       ['get', 'min_height']
  //     ],
  //     'fill-extrusion-opacity': 0.6
  //   }
  // })

  // map.loadImage('/images/lable/lable1.png', (error, image) => {
  //   if (error) {
  //     throw error
  //   }
  //   // Add the loaded image to the style's sprite with the ID 'kitten'.
  //   map.addImage('lable-1', image, {
  //     stretchX: [
  //       [28, 48],
  //       [86, 106]
  //     ],
  //     stretchY: [[15, 45]],
  //     content: [28, 15, 106, 45],
  //     pixelRatio: 2
  //   })
  //   map.addLayer({
  //     id: 'original',
  //     type: 'symbol',
  //     source: 'dlmc_point',
  //     layout: {
  //       'text-field': ['get', 'name'],
  //       'icon-image': 'lable-1',
  //       'icon-text-fit': 'both',
  //       'icon-allow-overlap': false,
  //       'text-allow-overlap': false,
  //       'text-size': 12
  //     },
  //     paint: {
  //       'text-color': 'rgb(54,153,255)'
  //     }
  //   })
  // })

  // parameter.typeName = 'sqsf:shumu'
  // const treeData = await api
  //   .getLayerData('sqsf', parameter)
  //   .catch((err) => console.log(err))

  // console.log('树木', treeData)
  // map.addSource('shumu', {
  //   type: 'geojson',
  //   data: treeData
  // })

  // map.addLayer({
  //   id: 'shumu',
  //   type: 'symbol',
  //   source: 'shumu',
  //   layout: {
  //     'icon-image': ['get', 'alias'],
  //     'icon-allow-overlap': false,
  //     'text-allow-overlap': false
  //   }
  // })

  // parameter.typeName = 'sqsf:jianzhuwulabel'
  // const buildingLabelData = await api
  //   .getData2(parameter)
  //   .catch((err) => console.log(err))

  // map.addSource('jianzhuwulabel', {
  //   type: 'geojson',
  //   data: buildingLabelData
  // })
  // map.addLayer({
  //   id: 'jianzhuwulabel',
  //   type: 'symbol',
  //   source: 'jianzhuwulabel',
  //   layout: {
  //     'text-field': ['get', 'name'],
  //     'text-size': 11,
  //     'text-letter-spacing': 0.2,
  //     'text-offset': [0, -1]
  //   },
  //   paint: {
  //     'text-color': '#181818',
  //     'text-halo-color': 'rgba(255, 255,255, 1)', // 光影效果
  //     'text-halo-width': 1.5 // 光影效果
  //   }
  // })

  // map.U.clickLayer('buildings', (e) => {
  //   removePopups()
  //   const name = e.features[0].properties.name
  //   // console.log('featureProperties', e);
  //   // const position2D = featureProperties.lonlatTwodim.split(',')

  //   if (name) {
  //     const popupHtml2D = '<div class="popup-simple">' + name + '</div>',
  //       popup = new mapboxgl.Popup({
  //         className: 'map-click-popup',
  //         maxWidth: '400px',
  //         closeButton: false,
  //         offset: [0, -15]
  //       }).setHTML(popupHtml2D)

  //     popup.setLngLat(e.lngLat).addTo(map)
  //     popups.push(popup)
  //   }
  //   e.preventDefault()
  // })
}

// 加载贴图建筑
async function addChartletLyer() {
  window.tb = new Threebox(map, map.getCanvas().getContext('webgl'), {
    defaultLights: true
  })
  const parameter = {
    service: 'WFS',
    version: '1.0.0',
    request: 'GetFeature',
    maxFeatures: '10000',
    outputFormat: 'application/json',
    typeName: 'zzdx:building_simple'
  }
  const data = await api.getLayerData('zzdx', parameter).catch((err) => console.log(err))

  // molayersData = layerJson.data
  setTimeout(() => {
    addChartletLayer(data.features)
  }, 100)
}

function addChartletLayer(features) {
  map.addLayer({
    id: 'sqsfchartlet_layer',
    type: 'custom',
    renderingMode: '3d',
    onAdd: function (map, mbxContext) {
      addBuildings(features)
    },
    render: function (gl, matrix) {
      tb.update()
    }
  })
}

function addBuildings(data) {
  data.forEach((b) => {
    if (b.geometry) {
      if (b.geometry.coordinates) {
        const coordinate = b.geometry.coordinates
        creatChartlet(b, coordinate)
        // console.log('coordinates', b.geometry.coordinates)
        // for (const coordinate of b.geometry.coordinates) {
        // const polygon = turf.polygon([coordinate])
        // const center = turf.centerOfMass(polygon).geometry.coordinates
        // const texture = new THREE.TextureLoader().load(path + 'images/material/floors5.png')
        // texture.wrapS = texture.wrapT = THREE.RepeatWrapping
        // texture.repeat.set(1, parseInt(b.properties.height / 8)) //重复产生N个相同贴图 产生N行
        // // texture.offset.set(0, 0.5)
        // const material1 = new THREE.MeshBasicMaterial({
        //   // color: '#999999',
        //   transparent: true,
        //   opacity: 0.7,
        //   map: texture
        // })
        // material1.color.offsetHSL(0, 0.5, 0.5)
        // const material = new THREE.MeshBasicMaterial({
        //   color: 'rgb(0,154,153)',
        //   transparent: true,
        //   opacity: 1
        // })
        // material.color.offsetHSL(0, 0.3, 0.3)
        // const extrusion = tb.extrusion({
        //   coordinates: [coordinate],
        //   geometryOptions: { curveSegments: 1, bevelEnabled: false, depth: b.properties.height / 30 },
        //   materials: [material, material1]
        // })
        // // extrusion.addTooltip(b.properties.tooltip, true)
        // extrusion.setCoords([center[0], center[1], 0])
        // tb.add(extrusion)
        // }
      }
    } else {
      console.log('coordinates', b)
    }
  })
}

function creatChartlet(b, coordinate) {

  // 建筑高度
  let jzdepth = b.properties.height
  // 如果有抬高属性就计算新的建筑高度
  if(b.properties.base_height) {
    jzdepth = b.properties.height - b.properties.base_height
  }
  // 计算建筑与30的比例，用来生成贴图与拉伸建筑
  const jzheightbl = (jzdepth / 30).toFixed(2)

  let textureRepeat
  if(b.properties.floor_ds) {
    textureRepeat = b.properties.floor_ds / jzheightbl
  } else{
    textureRepeat = jzdepth / 6 / jzheightbl
  }


  // const topimg = 'yxy3.jpg'
  const sideimg = 'shy4.jpg'
  const texture = new THREE.TextureLoader().load(path + 'images/material/' + sideimg)
  // const texture2 = new THREE.TextureLoader().load(path + 'images/material/' + topimg)
  texture.wrapS = texture.wrapT = THREE.RepeatWrapping
  texture.repeat.set(1, textureRepeat) // 重复产生N个相同贴图 产生N行
  // if (b.properties.name === '南风雨操场') {
  //   console.log('楼层贴图', b, parseInt(Number(b.properties.height) / 5))
  // }
  // texture.offset.set(20, 0)
  const material1 = new THREE.MeshBasicMaterial({
    color: b.properties.sz_color,
    transparent: true,
    opacity: 0.95,
    map: texture
  })
  // texture2.wrapS = texture2.wrapT = THREE.RepeatWrapping
  // texture2.repeat.set(5, 5) // 重复产生N个相同贴图 产生N行
  // texture2.offset.set(0, 0)
  const material = new THREE.MeshBasicMaterial({
    color: b.properties.color,
    transparent: true,
    opacity: 0.95
    // map: texture2
  })
  // material.color.offsetHSL(0, 0, 50)
  // const coords = [coordinate]
  // console.log('coordinates======================', coords)

  const extrusion = window.tb.extrusion({
    bbox: false,
    coordinates: coordinate,
    geometryOptions: { curveSegments: 1, bevelEnabled: false, depth: jzheightbl },
    materials: [material, material1]
  })
  // extrusion.addTooltip(b.properties.tooltip, true)
  // 计算模型中心点
  let center
  if (b.properties.centre) {
    center = b.properties.centre.split(',')
  } else {
    const polygon = turf.polygon(coordinate)
    center = turf.centerOfMass(polygon).geometry.coordinates
  }
  extrusion.setCoords([center[0], center[1], b.properties.base_height])
  // extrusion.setScale(0.5)
  extrusion.scale.set(0.95, 0.95, 0.95)
  // buildingModels.push(extrusion)
  // extrusion.addEventListener("SelectedChange", function (ent) {
  //   // 先删除其他模型的闪烁
  //   map.clearModelFlicker()
  //   // 点击后触发闪烁事件，给事件封装方法
  //   console.log('建筑选中', ent, buildingModels);
  //   map.modelFlicker(ent)
  // })
  window.tb.add(extrusion)
}


</script>

<style>
#mapbox-container {
  width: 100vw !important;
  height: 100vh !important;
}
</style>
